package servlet;

import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import entity.Book;
import entity.Order;
import entity.OrderItem;
import entity.User;
import service.OrderService;
import util.ActiveCodeUtils;

/**
 * Servlet implementation class CreatOrder
 */
public class CreateOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 封装
		Order order=new Order();
		try {
			BeanUtils.populate(order, request.getParameterMap());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//补全数据
		HttpSession session=request.getSession();
		User user=(User)session.getAttribute("user");
		@SuppressWarnings("unchecked")
		Map<Book, Integer> cart = (Map<Book, Integer>)session.getAttribute("cart");
		order.setUser(user);
		order.setId(ActiveCodeUtils.getUUID());
		//对应商品封装到订单条目
		for (Book b:cart.keySet()) {
			OrderItem orderItem=new OrderItem();
			orderItem.setOrder(order);
			orderItem.setBuynum(cart.get(b));
			orderItem.setP(b);
			order.getOrderItems().add(orderItem);		
		}
		//调用service生成订单
		OrderService service=new OrderService();
		service.addOrder(order);
		//显示订单数据
		response.sendRedirect(request.getContextPath() + "/client/createOrderSuccess.jsp");
	}

}
